package ee.ut.math.chess.hadoop;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;

import ee.ut.math.chess.base.model.Move;
import ee.ut.math.chess.game.model.Game;

public class Skeleton {
	private static Configuration conf;
	public static final String INPUT_PATH_BASE = "/user/root/ROGVchess/input/";
	public static final String OUTPUT_PATH_BASE = "/user/root/ROGVchess/output/";
	
	static {
		conf = new Configuration();
		conf.set("mapred.job.tracker", "hdfs://node0:9001/");
        conf.set("fs.default.name", "hdfs://node0:9000/");
	}
	
	public Move getMove(Game game) throws Exception {
		String pathout = OUTPUT_PATH_BASE + game.getId();
		String pathin = INPUT_PATH_BASE + game.getId();
		
		HadoopFsManager.writeGame(pathin + "/input", game);
		int result = run(pathin, pathout);
		
		if (result != 0) {
			return null;
		}
		
		java.util.Map<Double, List<Move>> moves = HadoopFsManager.readMoves2(pathout);
		
		List<Double> keys = new ArrayList<Double>(moves.keySet());
		System.out.println(keys);
		System.out.println(moves.values());
		Collections.sort(keys);
		Double key = keys.get(keys.size()-1);
		System.out.println(" KEY selected is: " + key);
		
		HadoopFsManager.deleteDirInHadoop(pathin);
		HadoopFsManager.deleteDirInHadoop(pathout);
		List<Move> list = moves.get(key);
		return list.get((int) (list.size()*Math.random()));
	}
	
	private int run(String pathin, String pathout) throws Exception {
		
		Job job = new Job(conf);
		job.setJarByClass(Skeleton.class);

		job.setMapperClass(Map.class);
		job.setReducerClass(Reduce.class);
        
		job.setInputFormatClass(SequenceFileInputFormat.class);
		job.setOutputFormatClass(SequenceFileOutputFormat.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(BytesWritable.class);
		
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(DoubleWritable.class);	
	
		FileInputFormat.addInputPath(job, new Path(pathin));
		FileOutputFormat.setOutputPath(job, new Path(pathout));

		boolean success = job.waitForCompletion(true);
		return success ? 0 : -1;
    }
	
}
